import 'package:flutter/material.dart';

// 父widget
class ParentWidget3 extends StatefulWidget {
  ParentWidget3({Key? key}) : super(key: key);

  @override
  State<ParentWidget3> createState() => _ParentWidget3State();
}

class _ParentWidget3State extends State<ParentWidget3> {
  // 父管理状态
  bool _active = false;
  // 父组件决定点击事件的处理
  void _handleChange(bool newValue) {
    setState(() {
      _active = newValue;
    });
  }

  @override
  Widget build(BuildContext context) {
    return ChildWidget(
      active: _active,
      onChanged: _handleChange,
    );
  }
}

// 子widget
class ChildWidget extends StatefulWidget {
  // 暴露给父组件管理的状态
  final bool active;
  final ValueChanged<bool> onChanged;

  ChildWidget({Key? key, this.active = false, required this.onChanged})
      : super(key: key);

  @override
  State<ChildWidget> createState() => _ChildWidgetState();
}

class _ChildWidgetState extends State<ChildWidget> {
  // 自身管理的状态
  bool _hightlight = false;

  void _handleTapDown(TapDownDetails details) {
    setState(() {
      _hightlight = true;
    });
  }

  void _handleTapUp(TapUpDetails details) {
    setState(() {
      _hightlight = false;
    });
  }

  void _handleTapCancle() {
    setState(() {
      _hightlight = false;
    });
  }

  void _handleTap() {
    // 子组件通过回调的方式将状态传给父组件，由父组件管理
    // 通过widget.xx调用给父组件管理的状态
    widget.onChanged(!widget.active);
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: _handleTap,
      onTapCancel: _handleTapCancle,
      onTapDown: _handleTapDown,
      onTapUp: _handleTapUp,
      child: Container(
          width: 80,
          height: 50,
          child: Center(
            child: Text(
              widget.active ? 'Active' : 'Not Active',
              style: TextStyle(
                fontSize: 32,
                color: Colors.white,
              ),
            ),
          ),
          decoration: BoxDecoration(
            color: widget.active ? Colors.green : Colors.grey,
            border:
                _hightlight ? Border.all(color: Colors.red, width: 10) : null,
          )),
    );
  }
}
